import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:get/get.dart';
import 'package:oi_ai_tool/config/ai_source.dart';
import 'package:oi_ai_tool/config/api_config.dart';
import 'package:oi_ai_tool/model/chat_message.dart';
import 'package:oi_ai_tool/model/request_token.dart';
import 'package:oi_ai_tool/services/user_service.dart';
import 'package:oi_ai_tool/util/http/http_request.dart';
import 'package:oi_ai_tool/util/http/intercept/sse.dart';
import 'package:oi_ai_tool/util/storage.dart';

class ChatService extends GetxService {
  UserService userService = Get.find<UserService>();
  @override
  onReady() {
    // init
  }

  _baiduChat(
      {required List<ChatMessage> chatLsit,
      required OnMsgCallBack onMsg}) async {
    var res = await OiHttpRequest().post(ApiConfiguration.baiduChat,
        params: {'access_token': userService.token},
        data: {
          "messages": ChatMessage.toListJson(chatLsit),
          "stream": true,
        },
        options: Options(responseType: ResponseType.stream, headers: {
          "Accept": "text/event-stream",
          "Cache-Control": "no-cache",
        }));
    SSE sse = SSE(res);
    sse.onMessage(onMsg: (data) {
      onMsg(data);
    });
  }

  chat(
      {required List<ChatMessage> chatLsit,
      required OnMsgCallBack onMsg}) async {
    var tokenData = await OiStorage.get(StoreageKey.TOKEN_KEY);
    if (tokenData != null) {
      RequestToken requestToken = RequestToken.formJson(jsonDecode(tokenData));
      String aiSource = requestToken.aiSource!;
      if (AiSource.BAIDU.type.compareTo(aiSource) == 0) {
        return await _baiduChat(chatLsit: chatLsit, onMsg: onMsg);
      } else if (AiSource.CHATGPT.type.compareTo(aiSource) == 0) {}
    }
  }
}
